#include "GameMain.h"

using namespace cocos2d;
using namespace CocosDenshion;

GameBgLayer::GameBgLayer()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}

GameBgLayer::~GameBgLayer()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}

void GameBgLayer::setBg(char *value)
{
	this->removeAllChildren();
	map = CCTMXTiledMap::create(value);
	this->addChild(map);
	map->setPosition(CCPointZero);
	layer = map->layerNamed("bg");
	CCPoint point = CCPointMake(-map->getContentSize().width / 2 + CCDirector::sharedDirector()->getWinSize().width / 2,-map->getContentSize().height / 2 + CCDirector::sharedDirector()->getWinSize().height / 2);
	GameMain::sharedGameMain()->getBgLayer()->setPosition(point);
	GameMain::sharedGameMain()->getHeroLayer()->setPosition(point);
	GameMain::sharedGameMain()->getGridLayer()->setPosition(point);
	GameMain::sharedGameMain()->getGridLayer()->drawGrid();
}

float GameBgLayer::getMapTileWidth()
{
	return map->getTileSize().width;
}

float GameBgLayer::getMapTileHeight()
{
	return map->getTileSize().height;
}

float GameBgLayer::getMapContentWidth()
{
	return map->getContentSize().width;
}

float GameBgLayer::getMapContentHeight()
{
	return map->getContentSize().height;
}

float GameBgLayer::getMapSizeWidth()
{
	return map->getMapSize().width;
}

float GameBgLayer::getMapSizeHeight()
{
	return map->getMapSize().height;
}

bool GameBgLayer::getFlag(float x,float y)
{
	CCDictionary *a = map->propertiesForGID(layer->tileGIDAt(ccp(x,y)));
	
	a->allKeys();
	if(a->valueForKey("flag")->getCString() == string("1"))
	{
		return false;
	}
	return true;
}


float initX;
float initY;
bool GameBgLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	initX = GameMain::sharedGameMain()->getBgLayer()->getPositionX();
	initY = GameMain::sharedGameMain()->getBgLayer()->getPositionY();
	return true;
}
void GameBgLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
	CCPoint point = pTouch->getLocation();
	CCPoint start = pTouch->getStartLocation();
	int X = initX + point.x - start.x;
	int Y = initY + point.y - start.y;

	if(X > 0)
		X = 0;
	if(Y > 0)
		Y = 0;
	if(-X + CCDirector::sharedDirector()->getWinSize().width > map->getContentSize().width)
		X = -(map->getContentSize().width - CCDirector::sharedDirector()->getWinSize().width);
	if(-Y + CCDirector::sharedDirector()->getWinSize().height > map->getContentSize().height)
		Y = -(map->getContentSize().height - CCDirector::sharedDirector()->getWinSize().height);


	GameMain::sharedGameMain()->getBgLayer()->setPosition(X,Y);
	GameMain::sharedGameMain()->getHeroLayer()->setPosition(X,Y);
	GameMain::sharedGameMain()->getGridLayer()->setPosition(X,Y);
}

void GameBgLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
}

void GameBgLayer::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
}